package com.liao.domain.strategy.service.raffle;

import com.liao.domain.strategy.model.entity.StrategyAwardEntity;
import com.liao.domain.strategy.model.valobj.RuleTreeVO;
import com.liao.domain.strategy.model.valobj.StrategyAwardRuleModelVO;
import com.liao.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.liao.domain.strategy.service.AbstractRaffleStrategy;
import com.liao.domain.strategy.service.IRaffleAward;
import com.liao.domain.strategy.service.IRaffleStock;
import com.liao.domain.strategy.service.rule.chain.ILogicChain;
import com.liao.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.liao.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import com.liao.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/*
 * @Author:  long
 * @Description: 默认的抽奖策略实现
 * @date:  2024-08-03 14:47
 */
@Slf4j
@Service
public class DefaultRaffleStrategy extends AbstractRaffleStrategy implements IRaffleStock, IRaffleAward {

    @Override
    public DefaultChainFactory.StrategyAwardVO raffleLogicChain(String userId, Long strategyId) {
        ILogicChain iLogicChain = defaultChainFactory.openLogicChain(strategyId);
        return iLogicChain.logic(userId, strategyId);
    }

    @Override
    public DefaultTreeFactory.StrategyAwardVO raffleLogicTree(String userId, Long strategyId, Long awardId) {
        StrategyAwardRuleModelVO strategyAwardRuleModelVO = strategyRepository.queryStrategyAwardRuleModelVO(strategyId, awardId);
        if (null == strategyAwardRuleModelVO) {
            //没有配置中置规则
            return DefaultTreeFactory.StrategyAwardVO.builder().awardId(awardId).build();
        }
        RuleTreeVO ruleTreeVO = strategyRepository.queryRuleTreeVOByTreeId(strategyAwardRuleModelVO.getRuleModels());
        IDecisionTreeEngine decisionTreeEngine = defaultTreeFactory.openLogicTree(ruleTreeVO);
        return decisionTreeEngine.process(userId,strategyId,awardId);
    }

    @Override
    public StrategyAwardStockKeyVO takeQueueValue() throws InterruptedException {
        return strategyRepository.takeQueueValue();
    }

    @Override
    public void updateStrategyAwardStock(Long strategyId, Long awardId) {
        strategyRepository.updateStrategyAwardStock(strategyId, awardId);
    }

    @Override
    public List<StrategyAwardEntity> queryRaffleStrategyAwardList(Long strategyId) {
        return strategyRepository.queryStrategyAwardList(strategyId);
    }
}
